package com.study.juc.cf;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * @program: juc-study
 * @author: Zhoujian
 * @date: 2022-08-12 14:11
 * @version: 1.0
 * @description: 多线程执行任务练习
 **/
class MyTask extends RecursiveTask<Integer> {
	private static final Integer ADJUST_VALUE = 10;
	private final int begin;
	private final int end;
	private int result;

	public MyTask(int begin, int end) {
		System.out.println(Thread.currentThread().getName() + "构造方法执行");
		this.begin = begin;
		this.end = end;
	}

	@Override
	protected Integer compute() {
		if ((end - begin) <= ADJUST_VALUE) {
			for (int i = begin; i <= end; i++) {
				result = result + i;
			}
			System.out.println(Thread.currentThread().getName() + "返回结果ADJUST_VALUE：" + result);
		} else {
			int middle = (begin + end) / 2;
			MyTask task01 = new MyTask(begin, middle);
			MyTask task02 = new MyTask(middle + 1, end);
			task01.fork();
			task02.fork();
			result = task01.join() + task02.join();
			System.out.println(Thread.currentThread().getName() + "返回结果：" + result);
		}


		return result;
	}
}


/**
 * 分支合并例子
 * ForkJoinPool
 * ForkJoinTask
 * RecursiveTask
 */
public class ForkJoinDemo {

	public static void main(String[] args)  {

		MyTask myTask = new MyTask(0,100);

		ForkJoinPool forkJoinPool = new ForkJoinPool();
		ForkJoinTask<Integer> forkJoinTask = forkJoinPool.submit(myTask);

		System.out.println(forkJoinTask.join());

		forkJoinPool.shutdown();
	}
}